package com.bl.weilan.service.biz.news.impl;

import com.bl.weilan.common.utils.UUIDUtils;
import com.bl.weilan.dao.model.NewsEntity;
import com.bl.weilan.dao.repository.NewsRepository;
import com.bl.weilan.service.biz.news.NewsService;
import com.bl.weilan.service.vo.news.NewsAddVo;
import com.bl.weilan.service.vo.news.NewsListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.log4j.Log4j2;
import com.bl.weilan.common.ApiResponseCode;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import java.util.Date;
import com.bl.weilan.service.vo.DelBody;
import com.bl.weilan.service.vo.DelListBody;
import com.bl.weilan.common.CommonServiceException;
import com.bl.weilan.service.vo.news.NewsModVo;

/**
 * Created by liangweikang on 19/6/24.
 */
@Service
@Log4j2
public class NewsServiceImpl implements NewsService{
    @Autowired
    NewsRepository newsRepository;

    @Override
    public NewsEntity getNewsById(String newsId) {
        NewsEntity newsEntity = newsRepository.findOne(newsId);
        return newsEntity;
    }

    @Override
    public NewsListVo getNewsLists(String type, Pageable pageable ){
        Page <NewsEntity> newsEntities;
        NewsListVo newsListVo = new NewsListVo();
        if(type.isEmpty() || "ALL".equals(type)) {
            newsEntities = newsRepository.findByOrderByWeightDesc(pageable);
        } else {
            newsEntities = newsRepository.findByTypeOrderByWeightDesc(type, pageable );
        }

        newsListVo.setTotalCount(newsEntities.getTotalElements());
        newsListVo.setList(newsEntities.getContent());

        return newsListVo;
    }

    @Override
    public void addNews(NewsAddVo newsAddVo) {
        NewsEntity newsEntity = new NewsEntity();
        newsEntity.setId(UUIDUtils.getUUID());
        newsEntity.setCreateTime(new Date());
        newsEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(newsAddVo, newsEntity);
        newsRepository.save(newsEntity);

    }

    @Override
    public void del(DelBody id) {
        newsRepository.delete(id.getId());
    }

    @Override
    public void delList(DelListBody idList) {
        for(String id : idList.getList()) {
            newsRepository.delete(id);
        }
    }

    @Override
    public void modify(NewsModVo newsModVo){
        NewsEntity newsEntity = newsRepository.findOne(newsModVo.getId());

        if (newsEntity == null) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "没有对应信息");
        }
        newsEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(newsModVo, newsEntity);
        newsRepository.save(newsEntity);
    }

}
